﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ShopSpace.Core;
using DotNetNuke.Common;

namespace ShopSpace.UI.DotNetNukeModules
{
	public partial class ViewProjects : ModuleControlBase
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			try
			{
				if (!Page.IsPostBack)
				{
					this.SetupLinks();
					this.BindProjects();
				}
			}
			catch (Exception ex)
			{
				this.HandleException(ex);
			}
		}

		protected void gvProjects_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				Project project = (Project)e.Row.DataItem;

				Label lblName = (Label)e.Row.FindControl("lblName");
				lblName.Text = project.Name;

				HyperLink hlEdit = (HyperLink)e.Row.FindControl("hlEdit");
				hlEdit.NavigateUrl = EditUrl("Id", project.Id.ToString(), "EditProject");

				HyperLink hlProjectPersons = (HyperLink) e.Row.FindControl("hlProjectPersons");
				hlProjectPersons.NavigateUrl = EditUrl("Id", project.Id.ToString(), "ViewProjectPersons");

				HyperLink hlMilestones = (HyperLink) e.Row.FindControl("hlMilestones");
				hlMilestones.NavigateUrl = EditUrl("Id", project.Id.ToString(), "ViewMilestones");

				LinkButton lnkDelete = (LinkButton)e.Row.FindControl("lnkDelete");
				lnkDelete.CommandName = "DeleteProject";
				lnkDelete.CommandArgument = e.Row.RowIndex.ToString();
				lnkDelete.Attributes.Add("onclick", "return confirm('Are you sure you want to delete this project?');");
			}
		}


		protected void gvProjects_RowCommand(object sender, GridViewCommandEventArgs e)
		{
			try
			{
				if (e.CommandName == "DeleteProject")
				{
					int rowIndex = Convert.ToInt32(e.CommandArgument);
					int projectId = Convert.ToInt32(this.gvProjects.DataKeys[rowIndex].Value);
					Project toDelete = this.ProjectRepository.Get(projectId);
					this.ProjectRepository.Delete(toDelete, this.UserInfo.Username);
					Response.Redirect(Globals.NavigateURL());
				}
			}
			catch (Exception ex)
			{
				this.HandleException(ex);
			}
		}

		
		private void BindProjects()
		{
			this.gvProjects.DataSource = this.ProjectRepository.ListByPortal(this.PortalId);
			this.gvProjects.DataKeyNames = new string[] { "Id" };
			this.gvProjects.DataBind();
		}

		private void SetupLinks()
		{
			this.hlAdd.NavigateUrl = EditUrl("EditProject");
		}
	}
}